import ctypes
import sys
import os
from helper import *

# 在导入soui4py之前设置DLL路径
souiRootDir = os.path.dirname(os.path.abspath(__file__))
result = setup_soui_dll_path(souiRootDir)
if not result:
    print("Failed to setup SOUI DLL path")

try:
    from soui4py import *
    print("Successfully imported soui4py")
except ImportError as e:
    print(f"Failed to import soui4py: {e}")
    import traceback
    traceback.print_exc()

from events import *
from message import *

class MainDlg(SHostWnd):
    events = EventHandler()
    messages = MessageHandler()
    cur_value = 0
    # 当前操作, 0=null, 1=add, 2=sub, 3=mul, 4=div
    cur_op = 0
    def __init__(self):
        super().__init__(soui_factory.CreateHostWnd('LAYOUT:maindlg'))
        self.SetEventHandler(self.events)
        self.SetMsgHandler(self.messages)

        
    @events.EVENT_NAME_COMMAND('btn_close')
    def OnBtnClose(self):
        print('btn_close')
        self.DestroyWindow()
        
    @events.EVENT_NAME_HANDLER('btn_menu', Event.EVT_CMD)
    def OnBtnMenu(self, evt: SEvtArgs):
        sender = SWindow(evt.Sender())
        rect_sender = sender.GetWindowRect()
        rect_btn = self.ClientToScreen2(rect_sender)
        menu = soui_factory.CreateMenu()
        menu.LoadMenu('smenu:menu_test')
        r = menu.TrackPopupMenu(0x0100, rect_btn['left'], rect_btn['bottom'], self._hWnd,100)
        menu.Release()
        if(r == 101):
            print('menu_help')
        if(r == 102):
            print('menu_about')

    def OnBtnNumber2(self, id):
        edit = self.FindChildByID(200)
        text = edit.GetWindowText()
        edit.SetWindowText(text + id)
    @events.EVENT_ID_RANGE_COMMAND(100, 109)
    def OnBtnNumber(self, id):
        self.OnBtnNumber2(str(id-100))
    
    @events.EVENT_NAME_COMMAND('btn_dot')
    def OnBtnDot(self):
        self.OnBtnNumber2('.')

    def OnOp(self, op):
        self.cur_op = op
        edit = self.FindChildByID(200)
        text = edit.GetWindowText()
        self.cur_num = float(text)
        edit.SetWindowText('')
    @events.EVENT_NAME_COMMAND('btn_add')
    def OnBtnAdd(self):
        print('btn_add')
        self.OnOp(1)
        
    @events.EVENT_NAME_COMMAND('btn_sub')
    def OnBtnSub(self):
        print('btn_sub')
        self.OnOp(2)

    @events.EVENT_NAME_COMMAND('btn_mul')
    def OnBtnSub(self):
        print('btn_mul')
        self.OnOp(3)
    
    @events.EVENT_NAME_COMMAND('btn_div')
    def OnBtnSub(self):
        print('btn_div')
        self.OnOp(4)

    def OnEditInput(self, mode):
        print('edit_input', mode)
        edit = self.FindChildByID(200)
        text = edit.GetWindowText()
        if(mode == 1):#clear
            text = '0'
        if(mode == 2):#back
            text = text[:-1]
        if(mode == 3):#enter
            value = self.cur_num
            value2 = float(text)
            if(self.cur_op == 1):
                value += value2
            elif(self.cur_op == 2):
                value -= value2
            elif(self.cur_op == 3):
                value *= value2
            elif(self.cur_op == 4):
                if(value2 == 0):
                    value=0
                else:
                    value /= value2
            value = round(value, 2)
            self.cur_num = value
            self.cur_op = 0
            text = str(value)

        edit.SetWindowText(text)

    @events.EVENT_NAME_COMMAND('btn_clear')
    def OnBtnClear(self):
        print('btn_clear')
        self.OnEditInput(1)

    @events.EVENT_NAME_COMMAND('btn_backspace')
    def OnBtnBackspace(self):
        print('btn_backspace')
        self.OnEditInput(2)
    @events.EVENT_NAME_COMMAND('btn_enter')
    def OnBtnEnter(self):
        print('btn_enter')
        if(self.cur_op == 0):
            return
        self.OnEditInput(3)

def main():
    global soui_factory, app, decoder_factory, render_factory

    hinstance = getattr(sys, 'dllhandle', 0)
    soui_factory = SouiFactory(hinstance)
    if soui_factory.ptr() == None:
        print('创建SouiFactory失败!')
        return
    SOUI.SOUI_FACTORY = soui_factory

    decoder_factory = soui_factory.CreateImgDecoder_Stb()
    if decoder_factory.ptr() == None:
        print('创建DecoderFactory失败!')
        return
    SOUI.DECODER_FACTORY = decoder_factory

    render_factory = soui_factory.CreateRender_GDI()
    if render_factory.ptr() == None:
        print('创建RenderFactory失败!')
        return
    SOUI.RENDER_FACTORY = render_factory

    render_factory.SetImgDecoderFactory(decoder_factory)

    app = soui_factory.CreateApp(render_factory)
    if app.ptr() == None:
        print('创建App失败!')
        return
    SOUI.APP = app

    res_provider_system = soui_factory.CreateResProvider(RES_FILE)
    if not res_provider_system.Init('soui-sys-resource'):
        print('加载系统资源失败!')
        return
    app.LoadSystemNamedResource(res_provider_system)
    res_provider_system.Release()

    res_provider_user = soui_factory.CreateResProvider(RES_FILE)
    if not res_provider_user.Init('calc_res'):
        print('加载用户资源失败!')
        return
    res_provider_mgr = app.GetResProviderMgr()
    res_provider_mgr.AddResProvider(res_provider_user, 'uidef:xml_init') 

    dlg = MainDlg()
    
    dlg.Create()
    dlg.ShowWindow(1)
    
    nRet = app.Run(dlg.GetHwnd())
    
    
    dlg.Release()
    app.Release()
    soui_factory.Release()
    
    print('nRet:', nRet)

if __name__ == '__main__':
    main()
